﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pavilion.GameTools;

namespace Pavilion.Locks.Monitors
{
    public class KeyboardLockMonitor : LockMonitorBase
    {
        public override ILock Lock { get { return keyboardLock; } }

        private KeyboardLock keyboardLock;
        private KeyboardTool keyBoardTool;

        public KeyboardLockMonitor(KeyboardLock keyboardLock)
        {
            this.keyboardLock = keyboardLock;
        }

        public override void Dispose()
        {
            if (keyboardLock.IsPressed)
            {
                keyBoardTool.UnregisterKeyPressed(OpenLock, keyboardLock.Key);
                keyBoardTool.UnregisterKeyReleased(CloseLock, keyboardLock.Key);
            }
            else
            {
                keyBoardTool.UnregisterKeyPressed(CloseLock, keyboardLock.Key);
                keyBoardTool.UnregisterKeyReleased(OpenLock, keyboardLock.Key);
            }
        }

        public override void Load(GameItem gameItem)
        {
            keyBoardTool = gameItem.ObtainTool<KeyboardTool>();

            if (keyboardLock.IsPressed)
            {
                keyBoardTool.RegisterKeyPressed(OpenLock, keyboardLock.Key);
                keyBoardTool.RegisterKeyReleased(CloseLock, keyboardLock.Key);
            }
            else
            {
                keyBoardTool.RegisterKeyPressed(CloseLock, keyboardLock.Key);
                keyBoardTool.RegisterKeyReleased(OpenLock, keyboardLock.Key);
            }

            UpdateLock();
        }

        public override void UpdateLock()
        {
            IsOpen = keyBoardTool.GetKeyState(keyboardLock.Key, keyboardLock.IsPressed);
        }

        private void OpenLock() { IsOpen = true; }
        private void CloseLock() { IsOpen = false; }
    }
}
